<?php
namespace Api\Event;

use Think\Log;
/**
 * 资源上报
 */
class ResourceGroupEvent extends BaseEvent 
{

    const TYPE_VIDEO = 0;
    const TYPE_RACE  = 1;
    const TYPE_NEWS  = 2;

    const STATUS_DEL     = -1;
    const STATUS_PEDDING = 0;
    const STATUS_PASS    = 1;

    /**
     * 上报视频
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function storeVideo($data)
    {
        $resource = [
            'object_type' => self::TYPE_VIDEO, // 视频类型
            'object_id'   => $data['id'], // 视频id
            'uid'         => $data['uid'], // 用户id
            'game_id'     => $data['game_id'], // 游戏id
            'pub_time'    => "{$data['create_time']}.{$data['id']}".self::TYPE_VIDEO, // 时间.id.type 排序用
            'object'      => [],//$data, // 资源信息
            'status'      => $data['status'] ? self::STATUS_PASS : self::STATUS_PEDDING, // 状态
        ];
        $params = [
            'resources' => [$resource]
        ];
        try {
            $res = event('LocalClient')->doRequestByJson('resource_store', $params);
        } catch (\Exception $e) {
            \Think\Log::record('[LocalClient ADD_VIDEO ERROR] - '.$e->getMessage(), 'ERROR');
            $res = false;
        }
        return $res;
    }

    /**
     * 更新视频
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function updateVideo($data = [])
    {
        if (empty($data)) {
            return;
        }
        $params = [];
        foreach ($data as $value) {
            $video = [
                'object_type'  => self::TYPE_VIDEO,
                'object_id'  => $value['id'],
            ];
            if (isset($value['status'])) {
                $video['status'] = $value['status'];
            }
            if (!empty($value['game_id'])) {
                $video['game_id'] = intval($value['game_id']);
            }
            $params[] = $video;
        }
        return $this->updateStatus($params);
    }

    /**
     * 上报比赛
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function storeRace($data)
    {
        $resource = [
            'object_type' => self::TYPE_RACE, // 比赛类型
            'object_id'   => $data['id'], // 比赛id
            'uid'         => 0, // 后台添加数据，uid=0
            'game_id'     => $data['game_id'], // 游戏id
            'pub_time'    => strtotime($data['race_time']).'.'.$data['id'].self::TYPE_RACE, // 时间.id.type 排序用
            'object'      => [],//$data, // 资源信息
            'status'      => self::STATUS_PEDDING, // 状态默认为禁用
        ];
        $params = [
            'resources' => [$resource]
        ];
        try {
            $res = event('LocalClient')->doRequestByJson('resource_store', $params);
        } catch (\Exception $e) {
            \Think\Log::record('[LocalClient ADD_RACE ERROR] - '.$e->getMessage(), 'ERROR');
            $res = false;
        }
        return $res;
    }

    /**
     * 更新比赛
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function updateRace($id = [])
    {
        if (empty($id)) {
            return;
        }
        $rgService = service('RaceGroup');
        $id = is_array($id) ? $id : [$id];
        $races = $rgService->where(['id' => ['$in' => $id]])->field('id,status,state,race_time,game_id')->select();
        $races = array_column($races, null, 'id');

        $resources = [];
        foreach ($id as $value) {
            $race = $races[$value];
            $status = self::STATUS_PEDDING;
            if (!empty($race['state']) && !empty($race['status']) && $race['status'] > 0) {
                $status = self::STATUS_PASS;
            }
            $resources[] = [
                'object_type' => self::TYPE_RACE,
                'object_id'   => $value,
                'status'      => $status,
                'game_id'     => $race['game_id'],
                'pub_time'    => strtotime($race['race_time']).'.'.$value.self::TYPE_RACE,
            ];
        }
        return $this->updateStatus($resources);
    }

    /**
     * 上报新闻
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function storeNews($data)
    {
        $resource = [
            'object_type' => self::TYPE_NEWS, // 新闻类型
            'object_id'   => $data['id'], // 新闻id
            'uid'         => 0, // 后台添加数据，uid=0
            'game_id'     => $data['game_id'], // 游戏id
            'pub_time'    => $data['create_time'].'.'.$data['id'].self::TYPE_NEWS, // 时间.id.type 排序用
            'object'      => [],//$data, // 资源信息
            'status'      => $data['status'] ? self::STATUS_PASS : self::STATUS_PEDDING,
        ];
        $params = [
            'resources' => [$resource]
        ];
        try {
            $res = event('LocalClient')->doRequestByJson('resource_store', $params);
        } catch (\Exception $e) {
            \Think\Log::record('[LocalClient ADD_NEWS ERROR] - '.$e->getMessage(), 'ERROR');
            $res = false;
        }
        return $res;
    }

    /**
     * 更新新闻状态
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function updateNews($id = [])
    {
        if (empty($id)) {
            return;
        }
        $service = service('News');
        $id = is_array($id) ? $id : [$id];
        $newslist = $service->where(['id' => ['$in' => $id]])->field('id,type,status,create_time,game_id')->select();
        $newslist = array_column($newslist, null, 'id');

        $resources = [];
        foreach ($id as $value) {
            $news = $newslist[$value];
            $status = self::STATUS_PEDDING;
            if ($news['type'] == 0 && $news['status'] > 0) {
                $status = self::STATUS_PASS;
            }
            $resources[] = [
                'object_type' => self::TYPE_NEWS,
                'object_id'   => $value,
                'status'      => $status,
                'game_id'     => $news['game_id'],
                'pub_time'    => $news['create_time'].'.'.$value.self::TYPE_NEWS,
            ];
        }
        return $this->updateStatus($resources);
    }

    private function updateStatus($resources = [])
    {
        $params = ['resources' => $resources];
        try {
            $res = event('LocalClient')->doRequestByJson('resource_update', $params);
        } catch (\Exception $e) {
            \Think\Log::record('[LocalClient UPDATE ERROR] - '.$e->getMessage(), 'ERROR');
            $res = false;
        }
        return $res;
    }

    public function lists($games = [], $uids = [], $query = [], $limit = 10, $field = 'object_type,object_id,pub_time')
    {
        $query['status'] = self::STATUS_PASS;
        if (empty($query['pub_time'])) {
            $query['pub_time'] = ['$lt' => strval(NOW_TIME)];
        }

        $where = [];
        foreach ($query as $key => $value) {
            $where['$and'][][$key] = $value;
        }

        if (!empty($games)) {
            $or[]['$and'] = [
                [
                    'object_type' => ['$in' => [self::TYPE_NEWS, self::TYPE_VIDEO, self::TYPE_RACE]]
                ],
                [
                    'game_id' => ['$in' => $games]
                ]
            ];
        }
        if (!empty($uids)) {
            $or[]['$and'] = [
                [
                    'object_type' => self::TYPE_VIDEO
                ],
                [
                    'uid' => ['$in' => $uids]
                ]
            ];
        }
        if (!empty($or)) {
            $where['$and'][]['$or'] = $or;
        }
        $res = service('ResourceGroup')->where(['_array' => $where])
                                       ->order('pub_time desc')
                                       ->limit($limit)
                                       ->field($field)
                                       ->select();

        // echo service('ResourceGroup')->_sql();exit;
        return $res ? array_values($res) : [];
    }
}